(function(global){    
    
    var MathUtil = {};
    
    /**
     * @static
     * @method random.
     */
    MathUtil.random = (function() {
        var _random = Math.random;
        //生成指定区间[min, max)内的随机整数,默认生成区间[0,1)内的浮点数.
        return function(min, max) {
            if ( typeof min === 'undefined') {
                return _random();
            } else if ( typeof max === 'undefined') {
                max = Number.MAX_VALUE;
            }
            return Math.floor(_random() * (max - min)) + min;
        };
    })();    
    
    /**
     * 根据开始点与结束点的经纬度,计算两点之间距离.
     * @static
     * @param {Number} startLatitude
     * @param {Number} startLongitude
     * @param {Number} endLatitude
     * @param {Number} endLongitude
     */
    MathUtil.getDistance = function(startLatitude, startLongitude, endLatitude, endLongitude) {
        var earthRadius = 6371;
    
        var lat1 = (Math.PI / 180) * startLatitude;
        var lat2 = (Math.PI / 180) * endLatitude;
    
        var lon1 = (Math.PI / 180) * startLongitude;
        var lon2 = (Math.PI / 180) * endLongitude;
    
        //两点间距离(km).
        var distance = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * earthRadius;
        return distance * 1000;
    };
    /**
     * Find the nth Fibonacci number.
     * @static
     * @param {Number} n
     * @return {Number}
     */
    MathUtil.fibonacci = function(n) {    
        var g = (1 + Math.sqrt(5)) / 2;
        return Math.round((Math.pow(g,n) - Math.pow(-g,-n)) / Math.sqrt(5));
    };
    /**
     * Return the logarithm of n using base b
     * @param {Number} x
     * @param {Number} b
     */
    MathUtil.logN = function(x,b) {
        if (b == 2)
            return Math.LOG2E * Math.log(x);
        if (b == 10)
            return Math.LOG10E * Math.log(x);
        return Math.log(x) / Math.log(b);
    };
    /**
     * Return the nth root of x
     * @param {Number} x
     * @param {Number} n
     */
    MathUtil.nRoot = function(x,n) {
        var y = Math.log(x) / n;
        return Math.pow(Math.E,y);
    };
    /**
     * 碰撞检测
     * @param {Object} rectA
     * @param {Object} rectB
     */
    MathUtil.collisionDetect = function(rectA, rectB){
         return !(rectB.x1 > rectA.x2 || rectB.y1 > rectA.y2 || rectB.x2 < rectA.x1 || rectB.y2 < rectA.y1);
    };
    
    //----------------------------------------------------------------------------------------
    
    //TODO 兼容性代码.    
    ujs.extend(window.Math, MathUtil);    
    
    ujs.define('math', 'ujs', function(){
        return MathUtil;
    });
    
})(window);